package jeu;
import java.io.*;
import java.net.*;
import java.util.LinkedList;

import messages.*;

class ClientData {
	public Socket socket;
	public ObjectOutputStream oos;
	public ObjectInputStream ois;
	
	public ClientData(Socket socket_, OutputStream outputStream, 
			InputStream inputStream) throws Exception {
		socket = socket_;
		oos = new ObjectOutputStream(outputStream);
		ois = new ObjectInputStream(inputStream);	
	}
}

public class Server {
	private ServerSocket serverSocket;
	private int port;
	private LinkedList<ClientData> clients;
	private Jeu jeu;
	
	public Server(int port_) throws Exception {
		port = port_;
		serverSocket = new ServerSocket(port);
		clients = new LinkedList<ClientData>();
		System.out.println("Server running on port " + port);
	}
	
	private void acceptClient() throws Exception {
		Socket socket = serverSocket.accept(); //Wait for a client that connects to the socket
		ClientData client = new ClientData(socket, socket.getOutputStream(), 
				socket.getInputStream());
		clients.add(client);
		System.out.println("Accepted a connection from: "+
				client.socket.getInetAddress());
		
		//Send a message to the client with its id in the server
		client.oos.writeObject(new ConnectionMessage(clients.size() - 1));
	}
	
	public void run() throws Exception {
		System.out.println("Waiting for players.");
		while(clients.size() < 4) {
			acceptClient();
		}
		
		
		choisirDePrendre();
	}
	
	public void choisirDePrendre() throws Exception {
		boolean carteAEtePrise = false;
		int tour = 0;
		Carte cartePrise = jeu.distribuerPremieresCartes();
		DemandeQuiPrendMessage message = new DemandeQuiPrendMessage(cartePrise);
		int couleurChoisie = -1;
		int joueurquiapris = -1;
		
		while (!carteAEtePrise && tour < 2) {
			tour++;
			for (int i = 0; i < 4; i++) {
				clients.get(i).oos.writeObject(message);
				ReponseQuiPrendMessage reponse = (ReponseQuiPrendMessage) clients.get(i).ois.readObject();
				if (reponse.getVeutPrendre()) {
					if (tour == 1 && reponse.getCouleur() != cartePrise.getCouleur()) {
						ErrorMessage error = new ErrorMessage("Vous ne pouvez pas choisir cette couleur.");
						clients.get(i).oos.writeObject(error);
						i--;
					} else if (tour == 2 && reponse.getCouleur() == cartePrise.getCouleur()) {
						ErrorMessage error = new ErrorMessage("Vous ne pouvez pas choisir cette couleur.");
						clients.get(i).oos.writeObject(error);
						i--;
					} else {
						joueurquiapris = i;
						couleurChoisie = reponse.getCouleur();
						carteAEtePrise = true;
						break;
					}
				}
			}
		}

		jeu.getAtout()[couleurChoisie] = true;
		jeu.distribuerCarteSuivantes(joueurquiapris, cartePrise);
	}
	
	public void premierpli(int joueurquiapris){
		
	}
	
	public static void main(String[] args) {
		try {
			Server server = new Server(1234);
			server.run();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
